package com.tony.demo.widget;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tony.demo.R;

public class TouchEditText extends RelativeLayout implements OnTouchListener {
	private TextView mTextView;
	private EditText mEditText;

	public TouchEditText(Context context) {
		super(context);
		init();
		// TODO Auto-generated constructor stub
	}

	public TouchEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
		// TODO Auto-generated constructor stub
	}

	public TouchEditText(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	private void init() {
		View view = LayoutInflater.from(getContext()).inflate(R.layout.weight_edit_text, null);
		addView(view);
		mTextView = (TextView) view.findViewById(R.id.et_text);
		mEditText = (EditText) view.findViewById(R.id.et_edit_text);
		mTextView.setOnTouchListener(this);
	}

	@Override
	protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
		// TODO Auto-generated method stub
		if (!focused) {

		}
		super.onFocusChanged(focused, direction, previouslyFocusedRect);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			setActivated(true);
			setFocusable(true);
			requestFocus();
			invalidate();
			return true;
		}
		return super.onTouchEvent(event);
	}

	public void notifyOnTouchEvent() {
		InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromInputMethod(mEditText.getWindowToken(), 0);

		mEditText.setVisibility(View.GONE);
		mTextView.setVisibility(View.VISIBLE);
		mTextView.setText(mEditText.getText().toString());
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.et_text) {
			mTextView.setVisibility(View.GONE);
			mEditText.setVisibility(View.VISIBLE);

			mEditText.requestFocus();

			InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.showSoftInputFromInputMethod(mEditText.getWindowToken(), 0);
			return true;
		}

		if (getId() != R.id.et_edit_text && getId() != R.id.et_text) {
			mTextView.setVisibility(View.VISIBLE);
			mEditText.setVisibility(View.GONE);

			mTextView.setText(mEditText.getText().toString());
			return true;
		}
		return false;
	}

}
